package org.secur.eave.ui

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.shadowsocks.databinding.ActivityChoiceBinding
import org.secur.eave.adapter.NodeAdapter
import org.secur.eave.api.OnItemSelectedListener
import org.secur.eave.dao.StealthServer
import org.secur.eave.util.BaseUtil.Companion.convertStealthServer
import org.secur.eave.util.BaseUtil.Companion.fetchStealthLinkResult
import org.secur.eave.util.MMKVUtil

class ChoiceActivity : AppCompatActivity(), OnItemSelectedListener {
	private lateinit var bin: ActivityChoiceBinding
	private var selectedServer: StealthServer? = null  // 保存选中的 StealthServer 实例
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		bin = ActivityChoiceBinding.inflate(layoutInflater)
		setContentView(bin.root)
		initData()
		saveData()
	}
	
	private fun saveData() {
		bin.submit.setOnClickListener {
			selectedServer?.let { server ->
				val convertedServer = convertStealthServer(server)
				MMKVUtil.saveStringValue(convertedServer)
				finish()
			} ?: run {
				Toast.makeText(this, "No server selected", Toast.LENGTH_SHORT).show()
			}
		}
	}
	
	private fun initData() {
		fetchStealthLinkResult(
			onSuccess = { result ->
				val adapter = NodeAdapter(this@ChoiceActivity, result, this) // 传入 this 作为 listener
				bin.rcv.apply {
					this.adapter = adapter
					layoutManager = LinearLayoutManager(this@ChoiceActivity)
				}
				
				bin.progress.visibility = View.GONE
			},
			onFailure = { throwable ->
				Toast.makeText(this@ChoiceActivity, "Network error", Toast.LENGTH_SHORT).show()
			}
		)
	}
	
	override fun onItemSelected(position: Int, server: StealthServer) {
		selectedServer = server  // 保存选中的 StealthServer 实例
	}
}
